<template>
  <div class="update-avatar">
    <img :src="imgSrc" alt="" id="image" />
    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click="onConfirm">完成</span>
    </div>
  </div>
</template>

<script>
// 引入cropperjs图片裁切工具
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserAvatar } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  props: {
    imgSrc: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  mounted () {
    const image = document.getElementById('image')
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背
    })
    // console.log(cropper)
  },
  methods: {
    onConfirm () {
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        console.log(blob)
        // 创建formData数据
        const fd = new FormData()
        fd.append('photo', blob) // photo是因为接口的名字叫photo
        try {
          const { data: res } = await updateUserAvatar(fd)
          console.log(res)
          this.$emit('close') // 关闭弹出
          this.$emit('update', res.data.photo) // 更新头像
        } catch (err) {
          this.$toast.fail('上传失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.update-avatar {
  background: #000;
  width: 100%;
  height: 100vh;
  img {
    max-width: 100%;
    display: block;
    margin: 0 auto;
  }
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
